package jupitermouse.site.juc.demo.aqs.exchanger;

import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *     线程间交换数据.表示一种两个线程可以进行互相交换对象的会和点。
 * 只能用于两个线程之间，并且两个线程必须都到达汇合点才会进行数据交换
 * </p>
 *
 * @author jupiter
 */
public class ExchangerApp {
    private static final Exchanger<String> exchanger = new Exchanger<>();

    private static ExecutorService executorService = Executors.newFixedThreadPool(2);

    public static void main(String[] args) {
        executorData();
    }

    static void executorData(){

        executorService.execute(new Runnable() {
            @Override
            public void run() {
                String A = "银行流水A";
                try {
                    String B = exchanger.exchange(A);	// 交换我自己的数据 并且获取别人的数据

                    System.err.println("线程A: " + B);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        executorService.execute(new Runnable() {
            @Override
            public void run() {
                String B = "银行流水B";
                try {
                    String A = exchanger.exchange(B);	// 交换我自己的数据 并且获取别人的数据

                    System.err.println("线程B: " + A);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        executorService.shutdown();
    }


}
